# -*- coding: utf-8 -*-
"""
设备名称映射工具
支持将appledb.dev的HTML格式转换为IPSW API格式
"""

import sys
import io
import requests

if sys.platform == 'win32':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 常见设备的映射表
DEVICE_MAPPING = {
    # iPhone 15 系列
    'iPhone-15-Pro-Max': 'iPhone16,2',
    'iPhone-15-Pro': 'iPhone16,1',
    'iPhone-15-Plus': 'iPhone15,5',
    'iPhone-15': 'iPhone15,4',
    
    # iPhone 14 系列
    'iPhone-14-Pro-Max': 'iPhone15,3',
    'iPhone-14-Pro': 'iPhone15,2',
    'iPhone-14-Plus': 'iPhone14,8',
    'iPhone-14': 'iPhone14,7',
    
    # iPhone 13 系列
    'iPhone-13-Pro-Max': 'iPhone14,3',
    'iPhone-13-Pro': 'iPhone14,2',
    'iPhone-13': 'iPhone14,5',
    'iPhone-13-mini': 'iPhone14,4',
    
    # iPad 系列
    'iPad-Pro-12-9-inch-6th-generation': 'iPad14,6',
    'iPad-Pro-11-inch-4th-generation': 'iPad14,3',
    'iPad-Air-5th-generation': 'iPad13,16',
    'iPad-mini-6th-generation': 'iPad14,1',
}

def convert_device_name(device_input):
    """
    转换设备名称格式
    支持多种输入格式
    """
    # 移除.html后缀
    device_input = device_input.replace('.html', '')
    
    # 如果已经是iPhone16,2这种格式，直接返回
    if ',' in device_input and ('iPhone' in device_input or 'iPad' in device_input):
        return device_input
    
    # 查找映射表
    if device_input in DEVICE_MAPPING:
        return DEVICE_MAPPING[device_input]
    
    # 如果是从appledb.dev复制的URL
    if 'appledb.dev/device/' in device_input:
        device_name = device_input.split('/device/')[-1].replace('.html', '')
        if device_name in DEVICE_MAPPING:
            return DEVICE_MAPPING[device_name]
    
    return None

def get_device_mapping_from_api():
    """
    从IPSW API获取完整的设备映射
    """
    try:
        response = requests.get('https://api.ipsw.me/v4/devices', timeout=15)
        if response.status_code == 200:
            devices = response.json()
            mapping = {}
            for device in devices:
                name = device.get('name', '')
                identifier = device.get('identifier', '')
                if name and identifier:
                    # 转换为URL友好格式
                    url_name = name.replace(' ', '-').replace('(', '').replace(')', '').replace('"', '').replace(',', '')
                    mapping[url_name] = identifier
            return mapping
        return None
    except:
        return None

if __name__ == '__main__':
    print("=" * 80)
    print("设备名称格式转换工具")
    print("=" * 80)
    
    # 从命令行参数或交互输入获取设备名称
    if len(sys.argv) > 1:
        device_input = sys.argv[1]
    else:
        print("\n支持的输入格式:")
        print("  1. iPhone-15-Pro-Max (appledb.dev格式)")
        print("  2. iPhone-15-Pro-Max.html")
        print("  3. https://appledb.dev/device/iPhone-15-Pro-Max.html")
        print("  4. iPhone16,2 (IPSW格式)")
        device_input = input("\n请输入设备标识: ").strip()
    
    if not device_input:
        print("未输入设备标识")
        sys.exit(1)
    
    print(f"\n输入: {device_input}")
    print("-" * 80)
    
    # 转换
    result = convert_device_name(device_input)
    
    if result:
        print(f"转换结果: {result}")
        print(f"\n在 .env 文件中使用:")
        print(f"DEVICE_MODEL={result}")
    else:
        print("未找到匹配的设备")
        print("\n尝试从API获取完整映射...")
        
        mapping = get_device_mapping_from_api()
        if mapping:
            # 尝试模糊匹配
            search_term = device_input.lower().replace('.html', '').replace('https://appledb.dev/device/', '')
            matches = []
            for url_name, identifier in mapping.items():
                if search_term in url_name.lower():
                    matches.append((url_name, identifier))
            
            if matches:
                print(f"\n找到 {len(matches)} 个可能的匹配:")
                for url_name, identifier in matches[:10]:
                    print(f"  {url_name} → {identifier}")
                
                if matches:
                    print(f"\n建议配置:")
                    print(f"DEVICE_MODEL={matches[0][1]}")
            else:
                print("未找到匹配的设备")
                print("请运行: python find_device_model.py")
    
    print("\n" + "=" * 80)

